package es

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
	"jmicro/app/pkg/code"
	v1 "jmicro/app/user/srv/internal/dataSearch/v1"
	"jmicro/app/user/srv/internal/domain/do"
	metav1 "jmicro/pkg/common/meta/v1"
	"jmicro/pkg/errors"
)

type users struct {
	esClient *elastic.Client
}

var _ v1.UserSearchStore = &users{}

func NewUsersSearch(esClient *elastic.Client) v1.UserSearchStore {
	return &users{esClient: esClient}
}

type data struct {
	Name    string    `json:"name"`
	Age     int       `json:"age"`
	Company []company `json:"company"`
}

type company struct {
	Name string `json:"name"`
}

func (u *users) List(ctx context.Context, opts metav1.ListMeta) (*do.UserDOList, error) {
	result, err := u.esClient.Search().Index("account").Do(ctx)
	if err != nil {
		return nil, err
	}
	userse := data{}
	for _, value := range result.Hits.Hits {
		err = json.Unmarshal(value.Source, &userse)
		if err != nil {
			return nil, errors.WithCode(code.ErrEsUnmarshal, err.Error())
		}
	}
	fmt.Println(userse)
	return &do.UserDOList{}, nil
}
